package main;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import com.sun.javafx.runtime.VersionInfo;

public class AudioPlayer3 extends Application {
	private final SongModel songModel;

	private MetadataView metaDataView;
	private PlayerControlsView playerControlsView;

	public static void main(String[] args) {
		launch(args);
	}

	public AudioPlayer3() {
		songModel = new SongModel();
	}

	@Override
	public void start(Stage primaryStage) {
		System.out.println("JavaFX version: " + VersionInfo.getRuntimeVersion());
		songModel.setURL("file:/C:/Users/Public/Music/Sample%20Music/Kalimba.mp3");
		metaDataView = new MetadataView(songModel);
		playerControlsView = new PlayerControlsView(songModel);

		final BorderPane root = new BorderPane();
		root.setCenter(metaDataView.getViewNode());
		root.setBottom(playerControlsView.getViewNode());

		final Scene scene = new Scene(root, 800, 400);
		initSceneDragAndDrop(scene);

		// final URL stylesheet = getClass().getResource("media.css");
		// scene.getStylesheets().add(stylesheet.toString());

		primaryStage.setScene(scene);
		primaryStage.setTitle("Audio Player 3");
		primaryStage.show();
	}

	private void initSceneDragAndDrop(Scene scene) {
		scene.setOnDragOver(new EventHandler<DragEvent>() {
			@Override
			public void handle(DragEvent event) {
				Dragboard db = event.getDragboard();
				if(db.hasFiles() || db.hasUrl()) {
					event.acceptTransferModes(TransferMode.ANY);
				}
				event.consume();
			}
		});

		scene.setOnDragDropped(new EventHandler<DragEvent>() {
			@Override
			public void handle(DragEvent event) {
				Dragboard db = event.getDragboard();
				String url = null;

				if(db.hasFiles()) {
					url = db.getFiles().get(0).toURI().toString();
				}
				else if(db.hasUrl()) {
					url = db.getUrl();
				}

				if(url != null) {
					songModel.setURL(url);
					songModel.getMediaPlayer().play();
				}

				event.setDropCompleted(url != null);
				event.consume();
			}
		});
	}

}
